package com.bib.ciglog.data;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class FileData implements Data {

	private static String filename = "cigLogger.data";
	private String fullPath = null;
	private static String FIELD_SEP = ",";
	private static String ENTRY_SEP = ":";
	private List<CigObj> cigs;
	boolean init = false;



	//used to sort cigs
	private class cigComparator implements Comparator<CigObj>{
		@Override
		public int compare(CigObj lhs, CigObj rhs) {
			return (new Long(rhs.getDate() - lhs.getDate()).intValue());
		}
	}

	@Override
	public List<CigObj> getCigs() {

		try {
			init();
		} catch (IOException e) {
			return null;
		}

		return cigs;		
	}

	@Override
	public boolean addCig(CigObj obj) {
		System.out.println("FileData : addCig");
		cigs.add(obj);
		Collections.sort(cigs, new cigComparator());
		return true;
		//		return addCigList(objs);
	}


	@Override
	public boolean addCigList(List<CigObj> objs) {
		//		try {
		//			write(CigToString(objs),true);
		//		} catch (IOException e) {
		//			// TODO Auto-generated catch block
		//			e.printStackTrace();
		//			return false;
		//		}
		cigs.addAll(objs);
		Collections.sort(cigs, new cigComparator());
		return true;
	}


	@Override
	public boolean replaceList(List<CigObj> objs) {
		try {
			write(CigToString(objs),false);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}


	@Override
	public void setExtraProp(String key, String value) {
		if (key.equals(Data.XTRA_FILE_PATH)){
			fullPath = value;
		}
	}




	private void init() throws IOException {
		System.out.println("init FileData");
		if (!init){
			File f = new File (fullPath + filename);
			if (!f.exists()){
				f.createNewFile();
			}
			cigs = StringToCig(read());
			System.out.println("Found " + cigs.size() + " cigs");
			Collections.sort(cigs, new cigComparator());
			init = true;
		}
	}


	private boolean write(String s, boolean append) throws IOException {

		BufferedWriter bw = new BufferedWriter(new FileWriter(fullPath + filename));

		try {
			bw.write(s);
		} finally {
			bw.flush();
			bw.close();
		}

		return true;
	}


	private String CigToString(List<CigObj> objs){
		StringBuilder sb = new StringBuilder();

		for (Iterator<CigObj> iterator = objs.iterator(); iterator.hasNext();) {
			CigObj cigObj = iterator.next();
			sb.append(cigObj.getType()).append(FIELD_SEP).append(cigObj.getDate());
			if (iterator.hasNext()){
				sb.append(ENTRY_SEP);
			}
		}
		return sb.toString();
	}

	private List<CigObj> StringToCig(String s){
		if (s == null | s.length() <= 0){
			System.out.println("Found empty/null string");
			return new ArrayList<CigObj>();
		}
		System.out.println("Found NON empty/null string : ");
		System.out.println(s);
		String[] entries = s.split(ENTRY_SEP);
		List<CigObj> objs = new ArrayList<CigObj>();
		for (int i = 0; i < entries.length; i++) {
			System.out.println("Cig nbr " + i);
			System.out.println(entries[i].length());
			String[] strObj = entries[i].split(FIELD_SEP);
			CigObj obj = new CigObj();
			obj.setType(Integer.parseInt(strObj[0].trim()));
			obj.setDate(Long.parseLong(strObj[1].trim()));
			objs.add(obj);
		}
		return objs;
	}

	private String read() throws IOException {
		System.out.println("Path " + fullPath + filename);
		FileReader fr = new FileReader(fullPath + filename);
		BufferedReader br = new BufferedReader(fr);
		StringBuilder sb = new StringBuilder();
		try {
			String line = br.readLine();
			while (line != null) {
				sb.append(line);
				sb.append('\n');
				line = br.readLine();
			}
		} finally {
			br.close();
		}

		return sb.toString();
	}

	@Override
	public void save() {
		System.out.println("FileData : save");
		replaceList(this.cigs);
	}

	@Override
	public void clearData() {
		this.cigs.clear();
		
		
		File f = new File (fullPath + filename);
		
		try {
			f.delete();
			f.createNewFile();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void removeCig(CigObj cig){
		cigs.remove(cig);
	}

}
